#!/usr/bin/env python3
"""
API密钥配置和验证工具
解决API密钥配置问题的完整方案
"""

import os
import sys
import json
import requests
from pathlib import Path

def setup_api_keys_directly():
    """直接设置API密钥到系统环境变量"""
    
    print("🔧 直接配置API密钥")
    print("=" * 50)
    
    # 用户提供的API密钥
    api_keys = {
        'ZHIPU_API_KEY': '30727dc8c3f4f577b47842aba9cba333.Vi2hoL7mpQ4FvcNx',
        'DASHSCOPE_API_KEY': 'ms-d6ce8080-6783-4c7a-9ce1-62d74bf52d48',
        'MODELSCOPE_API_KEY': 'ms-d6ce8080-6783-4c7a-9ce1-62d74bf52d48',
    }
    
    # 直接设置到os.environ
    for key, value in api_keys.items():
        os.environ[key] = value
        print(f"✅ 已设置: {key}")
    
    # 验证设置
    print("\n🔍 验证环境变量设置:")
    for key in api_keys:
        value = os.getenv(key)
        if value:
            masked = value[:8] + "..." + value[-4:] if len(value) > 12 else "***"
            print(f"   {key}: {masked}")
        else:
            print(f"   {key}: ❌ 未设置")
    
    return api_keys

def test_api_connectivity():
    """测试API连接性"""
    
    print("\n🔍 测试API连接性...")
    
    # 测试GLM (BigModel)
    glm_key = os.getenv('ZHIPU_API_KEY')
    if glm_key:
        print("\n📞 测试智谱GLM连接...")
        try:
            response = requests.post(
                'https://open.bigmodel.cn/api/paas/v4/chat/completions',
                headers={
                    'Authorization': f'Bearer {glm_key}',
                    'Content-Type': 'application/json'
                },
                json={
                    'model': 'glm-3-turbo',
                    'messages': [{'role': 'user', 'content': 'test'}],
                    'max_tokens': 10
                },
                timeout=10
            )
            
            if response.status_code == 200:
                print("✅ GLM API连接成功")
            elif response.status_code == 401:
                print("❌ GLM API密钥无效")
                print(f"   错误: {response.text}")
            else:
                print(f"⚠️ GLM API返回: {response.status_code}")
                
        except Exception as e:
            print(f"❌ GLM API连接失败: {e}")
    
    # 测试ModelScope
    modelscope_key = os.getenv('MODELSCOPE_API_KEY')
    if modelscope_key:
        print("\n📞 测试ModelScope连接...")
        try:
            response = requests.post(
                'https://api-inference.modelscope.cn/v1/chat/completions',
                headers={
                    'Authorization': f'Bearer {modelscope_key}',
                    'Content-Type': 'application/json'
                },
                json={
                    'model': 'Qwen/Qwen2.5-Coder-32B-Instruct',
                    'messages': [{'role': 'user', 'content': 'test'}],
                    'max_tokens': 10
                },
                timeout=10
            )
            
            if response.status_code == 200:
                print("✅ ModelScope API连接成功")
            elif response.status_code == 401:
                print("❌ ModelScope API密钥无效")
                print(f"   错误: {response.text}")
            else:
                print(f"⚠️ ModelScope API返回: {response.status_code}")
                
        except Exception as e:
            print(f"❌ ModelScope API连接失败: {e}")

def create_windows_setup_script():
    """创建Windows批处理脚本"""
    
    bat_content = """@echo off
echo 正在配置API密钥...

:: 设置API密钥
set DASHSCOPE_API_KEY=ms-d6ce8080-6783-4c7a-9ce1-62d74bf52d48
set ZHIPU_API_KEY=30727dc8c3f4f577b47842aba9cba333.Vi2hoL7mpQ4FvcNx
set MODELSCOPE_API_KEY=ms-d6ce8080-6783-4c7a-9ce1-62d74bf52d48

echo API密钥已设置完成
echo.
echo 正在验证API连接...
python validate_api_keys.py

echo.
echo 按任意键运行AI测试...
pause

python test_modelscope_ai_decision.py

echo.
pause"""

    with open('run_api_test.bat', 'w', encoding='utf-8') as f:
        f.write(bat_content)
    
    print("✅ 已创建 run_api_test.bat")

def main():
    """主函数"""
    
    print("🎯 API密钥配置和验证工具")
    print("=" * 60)
    
    # 1. 直接设置API密钥
    setup_api_keys_directly()
    
    # 2. 测试API连接
    test_api_connectivity()
    
    # 3. 创建Windows批处理脚本
    create_windows_setup_script()
    
    print("\n" + "=" * 60)
    print("📋 配置完成！")
    print("\n下一步操作:")
    print("1. 双击运行 run_api_test.bat")
    print("2. 或在命令行执行:")
    print("   python configure_api_keys.py")
    print("\n💡 注意事项:")
    print("- GLM密钥对应BigModel.cn平台")
    print("- Qwen密钥对应ModelScope平台")
    print("- 如果仍然失败，请检查密钥是否已激活")

if __name__ == "__main__":
    main()